/**
 * @Author: linzp
 * @Date: 2021/11/10/11:08
 */
public class twofen_demo {


    public static int GetNumberOfK(int [] array , int k) {
        //比如k是5 就找5的左和6的左的差即可
        int first =  binarySearch(array,k);
        int last =  binarySearch(array,k+1);
        // 若超出数组范围，则证明目标值出现的次数为0，否则，右边界减去左边界即能统计出目标出现的次数
        return (first==array.length || array[first]!=k)?0:last-first;
    }

    private static int binarySearch(int[] array, int k) {
        int l = 0,r=array.length-1;
        while(l<r){
            int mid = l + (r-l)/2;
            if(array[mid]<k){
                l =mid+1;
            }else {
                r = mid;
            }
        }
        return l;
    }

    public static void main(String[] args) {
        int[] arr = {1,2,2,2,3};
        System.out.println(GetNumberOfK(arr,2));
    }
}
